import React, {Component} from 'react'
import Header from "@/NewNewTodo/components/Header";
import Main from "@/NewNewTodo/components/Main";
import Footer from "@/NewNewTodo/components/Footer";
import {produce} from "immer";
import {ALL, COMPLETED} from "@/NewNewTodo/constants";
import {ACTIVE} from "@/NewNewTodo/constants";
import {random} from "lodash";

import './index.css'

class App extends Component {
  state = {
    list: [
      {
        title: '学习vue',
        isDone: false,
        id: 1
      },
      {
        title: '学习React',
        isDone: true,
        id: 2
      },
      {
        title: '学习Node',
        isDone: false,
        id: 3
      }
    ],
    status: ALL
  }

  delTodo = id => () => {
    // 获取到需要删除的数据的id
    this.setState({
      list: this.state.list.filter(item => item.id !== id)
    })
  }

  changeChecked = (id, isDone) => {
    this.setState(produce(state => {
      // 先找到点击的这条数据 ==> 通过id找到的
      const currentTodo = state.list.find(item => item.id === id)
      // 找到之后直接设置它的isDone属性即可
      currentTodo.isDone = isDone
    }))
  }

  changeStatus = (status) => () => {
    this.setState({
      status
    })
  }

  clearAll = () => {
    //  做什么事情
    //  将isDone属性为true的过滤掉
    this.setState({
      list: this.state.list.filter(item => !item.isDone)
    })
  }

  addTodo = (title) => {
    this.setState(produce(state => {
      state.list.push({
        title,
        id: random(100, 1000),
        isDone: false
      })
    }))
  }

  changeAllChecked = (e) => {
    console.log(e.target.checked)
    this.setState(produce(state => {
      state.list.forEach(item => {
        item.isDone = e.target.checked
      })
    }))
  }

  render() {

    const {status, list} = this.state
    // 专门用来做展示的，不能修改源数据
    // 区分展示的判断逻辑就是根据status的状态
    const showList = list.filter(item => {
      if (status === COMPLETED) {
        // 想要拿到的数据是什么？isDone == true
        return item.isDone
      }
      if (status === ACTIVE) {
        //拿到的数据 isDone = false
        return !item.isDone
      }

      return true
    })
    return (
      <section className="todoapp">
        <Header
          addTodo={this.addTodo}
        />
        <Main
          list={showList}
          delTodo={this.delTodo}
          changeChecked={this.changeChecked}
          changeAllChecked={this.changeAllChecked}
        />
        <Footer
          len={showList.length}
          status={this.state.status}
          changeStatus={this.changeStatus}
          clearAll={this.clearAll}
        />
      </section>
    )
  }
}


export default App
